import { useState, useEffect, useLayoutEffect } from 'react';
export const time = (nowTime?: string | number | Date) => {
  // 设置当前日期+1天
  // 自定义时间
  let diyDate: string | number | Date = new Date();
  //加1天
  diyDate = new Date(diyDate.setDate(diyDate.getDate() + 1));
  // 拼接日期 yyyy-MM-dd 注意月份要 + 1
  let year = diyDate.getFullYear();
  let month =
    diyDate.getMonth() + 1 > 9
      ? diyDate.getMonth() + 1
      : `0${diyDate.getMonth() + 1}`;
  let date =
    diyDate.getDate() > 9 ? diyDate.getDate() : `0${diyDate.getDate()}`;
  diyDate = `${year}-${month}-${date}`;
  //结果
  // console.log(diyDate);

  const [time, setTime] = useState('');
  useEffect(() => {
    {
      setTimeout(() => {
        setTime(showtime(nowTime || diyDate));
      }, 1000);
    }
  }, [time]);
  const showtime = (lastTime: string | number | Date = diyDate) => {
    const nowtime = new Date(), //获取当前时间
      endtime = new Date(lastTime); //定义结束时间

    const lefttime = endtime.getTime() - nowtime.getTime(), //距离结束时间的毫秒数
      leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)), //计算天数
      lefth = Math.floor((lefttime / (1000 * 60 * 60)) % 24), //计算小时数
      leftm = Math.floor((lefttime / (1000 * 60)) % 60), //计算分钟数
      lefts = Math.floor((lefttime / 1000) % 60); //计算秒数

    if (leftd === 0 && lefth === 0 && leftm === 0) {
      return lefts + '秒';
    } else if (leftd === 0 && lefth === 0) {
      return leftm + '分' + lefts + '秒';
    } else if (leftd === 0) {
      return lefth + '时' + leftm + '分' + lefts + '秒';
    } else {
      return leftd + '天' + lefth + '时' + leftm + '分' + lefts + '秒'; //返回倒计时的字符串
    }
  };

  return time;
};
